package com.zw.yzk.kabu.data.repository;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.store.GoodsStore;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.MallItemEntity;
import com.zw.yzk.kabu.data.network.service.MallItemService;
import com.zw.yzk.kabu.data.network.task.MallItemTask;
import com.zw.yzk.kabu.data.utils.SharedPrefrenceUtils;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/2/27.
 */

public class MallItemRepository extends CommonRepository {

    @Inject
    GoodsStore goodsStore;
    private Context context;

    @Inject
    public MallItemRepository(Context context) {
        this.context = context;
    }

    @Override
    protected Observable commonObserve(Task task) {
        String cache = SharedPrefrenceUtils.getString(context, SharedPrefrenceUtils.getMallKey());
        if (TextUtils.isEmpty(cache) || !((MallItemTask) task).getLocal) {
            return super.commonObserve(task);
        }
        try {
            return Observable.just(new Gson().fromJson(cache, MallItemEntity.class));
        } catch (Exception e) {
            e.printStackTrace();
            return super.commonObserve(task);
        }
    }

    @Override
    protected Observable connectServer(Task task) {
        MallItemService service = ServiceGenerator.createService(MallItemService.class);
        //加载网络数据
        return service.getGoodsList();
    }

    @Override
    protected Func1<MallItemEntity, Observable> getServerData() {
        return new Func1<MallItemEntity, Observable>() {
            @Override
            public Observable call(MallItemEntity entity) {
                saveGoodsList(entity);

                return Observable.just(entity);
            }
        };
    }

    /**
     * 保存商品列表
     */
    private void saveGoodsList(MallItemEntity entity) {
        SharedPrefrenceUtils.setValue(context, SharedPrefrenceUtils.getMallKey(), new Gson().toJson(entity));
    }
}
